package com.uziot.net.usoup.services;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author shidt
 * @version V1.0
 * @className UsoupService
 * @date 2021-06-04 12:54:17
 * @description
 */

public abstract class AbstractParsePageService implements ParsePageService {

    /**
     * 加载页面
     *
     * @param url    url
     * @param params 参数列表
     * @return DOM对象
     * @throws Exception 页面获取异常
     */
    @Override
    public Document parsePage(String url, Map<String, String> params) throws Exception {
        URL urlResource = new URL(url);
        String timeout = params.getOrDefault("timeout", "10000");
        return Jsoup.parse(urlResource, Integer.parseInt(timeout));
    }

    @Override
    public List<String> parseElements(Document document, String param, String type) {
        ArrayList<String> result = new ArrayList<>();
        if (StringUtils.equalsIgnoreCase(type, "Attribute")) {
            Elements elements = document.getElementsByAttribute(param);
            elements.forEach(ele -> {
                String text = ele.attr(param);
                result.add(text);
            });
            return result;
        }

        if (StringUtils.equalsIgnoreCase(type, "Text")) {
            Elements elements = document.getElementsByTag(param);
            elements.forEach(ele -> {
                String text = ele.parent().text();
                result.add(text);
            });
            return result;
        }
        return null;
    }
}
